// 配置axios
import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
import { config } from "./config";
const { default_headers, request_timeout } = config;
// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, //设置API的基础URL
  timeout: request_timeout,
});

// 请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig): any => {
    //  获取请求头
    const headers = config.headers || {};
    config.headers = headers;
    return config;
  },
  (error: AxiosError) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据进行处理
    return response;
  },
  (error: AxiosError) => {
    // 处理响应错误
    return Promise.reject(error);
  }
);

const request = (option: any) => {
  const {
    url,
    method,
    params,
    data,
    headersType,
    responseType,
    baseUrl = import.meta.env.VITE_API_URL,
    timeout,
  } = option;
  return instance({
    url: baseUrl + url,
    method,
    params,
    data,
    responseType: responseType,
    headers: {
      "Content-Type": headersType || default_headers,
    },
    timeout,
  });
};
// 导出axios请求方法
// GET
export function GET<T>(option: any) {
  return new Promise<T>((resolve, reject) => {
    request({
      method: "GET",
      responseType: "json",
      ...option,
    })
      .then((res: any) => {
        if (res.data.code == 0) {
          resolve(res.data.data as T);
        } else {
          reject(res.data.msg || "请求异常!");
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}
// POST
export function POST<T>(option: any) {
  return new Promise<T>((resolve, reject) => {
    request({
      method: "POST",
      responseType: "json",
      ...option,
    })
      .then((res: any) => {
        if (res.data.code == 0) {
          resolve(res.data.data as T);
        } else {
          reject(res.data.msg || "请求异常!");
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}
// PUT
export function PUT<T>(option: any) {
  return new Promise<T>((resolve, reject) => {
    request({
      method: "PUT",
      responseType: "json",
      ...option,
    })
      .then((res: any) => {
        if (res.data.code == 0) {
          resolve(res.data.data as T);
        } else {
          reject(res.data.msg || "请求异常!");
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}
// DELETE
export function DELETE<T>(option: any) {
  return new Promise<T>((resolve, reject) => {
    request({
      method: "DELETE",
      responseType: "json",
      ...option,
    })
      .then((res: any) => {
        if (res.data.code == 0) {
          resolve(res.data.data as T);
        } else {
          reject(res.data.msg || "请求异常!");
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}
